# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import random,json
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.db.models import Q
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from .models import Questions,Type,Tag,Answer
# Create your views here.
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
def kind(request,id=None,id2=None):
    try:
        res = Questions.objects.filter(type_id=id).all()#查询分类
    except:
        res=Questions.objects.filter(tag_id=id2).all()#查询标签
    if res :#如果有内容
        try:
            res=Questions.objects.filter(type_id=id,tag_id=id2).all()#如果有分类，再查标签
        except:
            res=Questions.objects.filter(tag_id=id2).all()#没有分类直接返回标签
            id2 = int(id2)
        else:
            if res:#如果返回的有内荣，模版里面判断
                id2 = int(id2)
                id = int(id)
            else:
                res = Questions.objects.filter(type_id=id).all()
                id=int(id)
    else:
        res=Questions.objects.all()
    return res,id,id2
def get_content(txt=None,id = None,id2=None):
    """
    根据指定的过滤条件获取内容
    :param id: 
    :param id2: 
    :return: 
    """
    type_id = None
    tag_id = None
    find_c=''
    biaoji=''
    res = None

    #
    #
    #
    if id is not None and id !=u'None':
        type_id = int(id)
    if id2 is not None and id2 != u'None':
        tag_id = int(id2)


    #
    if type_id and tag_id:
        res = Questions.objects.filter(type_id=type_id, tag_id=tag_id).all()  # 如果有分类，再查标签
    elif type_id:
        res = Questions.objects.filter(type_id=type_id).all()  # 查询分类
    elif tag_id:
        res = Questions.objects.filter(tag_id=tag_id).all()  # 查询标签
    elif txt != '' and txt is not None:
        res = Questions.objects.filter(Q(question__contains=txt) | Q(abstract__contains=txt)).all()
        find_c = txt
    else:
        res = Questions.objects.all()
        biaoji='biaoji'
    return res, type_id, tag_id,find_c,biaoji
@login_required
def index(request):
    id = request.GET.get('id')
    id2=request.GET.get('id2')
    txt=request.GET.get('find_content')
    user = request.user
    types = Type.objects.all()
    tag = Tag.objects.all()
    res,id,id2,find_c,biaoji = get_content(txt,id,id2,)
    paginator=Paginator(res,4)
    page=request.GET.get('page')
    try:
        post_list = paginator.page(page)
    except PageNotAnInteger:
        post_list = paginator.page(1)
    except EmptyPage:
        post_list = paginator.page(paginator.num_pages)
    content = {'user': user,'post':post_list,'type':types,'tag':tag,'id':id,'id2':id2,'find_content':find_c,'list':biaoji}
    return render(request, 'index.html', context=content)
@login_required
def ask(request):
    a=request.COOKIES.get('error')
    res=request.user
    if not res:
        return redirect('/auth/')
    type = Type.objects.all()
    tag = Tag.objects.all()
    content = {'user': res, 'type': type, 'tag': tag,'error':a}
    return render(request,'ask.html',context=content)
@login_required
def ask_question(request):
    if request.method=="POST":
        user=request.GET.get('user')
        tags=request.POST.get('tags')
        title=request.POST.get('title')
        post=request.POST.get('content')
        print tags, title,post
        if title and post !='':
            b=Type.objects.get(types=tags)
            a = User.objects.get(username=user)
            tag=random.randint(1,7)
            res=Questions(question=title,abstract=post,sub_user_id=a.id,type_id=b.id,tag_id=tag)
            res.save()
            return redirect('/question/')
        else:
            response = redirect('/question/askto/')
            response.set_cookie('error', 1, 1)
            return response
    else:
        return redirect('/auth/')
@csrf_exempt
def n_count(request):
    sts = request.POST.get('stat')
    a={}
    if sts=='1':
        id = request.POST.get('id')
        id = int(id)
        res = Questions.objects.get(id=id)
        res.against_count=res.against_count+1
        res.save()
        a['num']=res.against_count
    elif sts=='2':
        id=request.POST.get('id')
        id=int(id)
        res=Answer.objects.get(id=id)
        res.zan_count=res.zan_count+1
        res.save()
        a['num']=res.zan_count
    b=json.dumps(a)
    if request.POST:
        return HttpResponse(b,content_type='application/json')
    else:
        return HttpResponse('ok')
@login_required()
def ans(request):
    ans_id = request.GET['id']
    if request.method=="POST":
        user=request.user
        user_id=User.objects.get(username=user)
        ans=request.POST.get('answer')
        res=Answer(content=ans,ans_question_id=ans_id,ans_user_id=user_id.id)
        res.save()
        return redirect('/question/answer/?id=%s'%ans_id)
    else:
        question=Questions.objects.get(id=ans_id)
        num=question.against_count
        answer=question.answer_set.all()
        if not answer:
            answer=''
        type = Type.objects.all()
        tag = Tag.objects.all()
        content={'a':question,'type':type,'tag':tag,'answer':answer,'ans_id':ans_id,'against':num}
        return render(request,'answer.html',context=content)
def add_type(request):
    type=request.POST.get('type')
    res=Type(types=type)
    res.save()
    return redirect('/question/askto')
def delete_question(request):
    if request.method=='POST':
        a=request.POST.getlist('q_id')
        for n in a:
            res=Questions.objects.get(id=n)
            res.delete()
        return redirect('/question/delete_question')
    res=Questions.objects.all()
    return render(request,'delete_question.html',{'res':res})
@login_required()
def myanswer(request):
    user=request.user
    user_id=User.objects.get(username=user).id
    all_ans=User.objects.get(username=user).answer_set.all()
    dict1 = {}
    list2=[]
    for a in all_ans:
        q_id=a.ans_question_id
        dict1[q_id]=q_id
    for b in dict1.values():
        dict2 = {}
        ques=Questions.objects.get(id=b)
        ans=Answer.objects.filter(ans_question_id=ques,ans_user_id=user_id).all()
        dict2['ques']=ques
        dict2['ans']=ans
        list2.append(dict2)
    # paginator = Paginator(list2, 1)
    # page = request.GET.get('page')
    # try:
    #     list1 = paginator.page(page)
    # except PageNotAnInteger:
    #     list1 = paginator.page(1)
    # except EmptyPage:
    #     list1 = paginator.page(paginator.num_pages)
    return render(request,'answer2.html',context={'res':list2})